<template>
  <PageContainer>
    <Header title="编辑基础信息" />
    <view class="hb-p-4">
      <tm-form
        @submit="handleSubmit"
        layout="vertical"
        :model-value="formData"
        :margin="[0, 0]"
        :padding="[0, 0]"
        :border="false"
        :label-align="'top'"
        :transparent="true"
      >
        <view class="hb-bg-white hb-px-4 hb-py-3 hb-box-shadow-base hb-rounded-lg">
          <!-- 名称输入区域 -->
          <tm-form-item
            required
            field="name"
            label="名称"
            :border="false"
            :margin="[0, 0]"
            :rules="[{ required: true, message: '请输入名称' }]"
          >
            <TmInput
              v-model="formData.name"
              :height="88"
              :font-size="28"
              placeholder="深圳市高州商会南山分会"
              :maxlength="20"
            />
          </tm-form-item>

          <!-- 头像上传区域 -->
          <tm-form-item
            field="iconFileUrl"
            label="头像"
            :border="false"
            :margin="[0, 0]"
            :rules="[{ required: true, message: '请上传头像' }]"
          >
            <view class="hb-flex hb-items-center hb-gap-4">
              <TImage
                :src="formData.iconFileUrl"
                width="160rpx"
                height="160rpx"
                border-radius="16rpx"
                error-img-type="person"
              />
              <text
                class="hb-text-sm hb-text-[#2878FF] hb-py-1 hb-px-2 hb-inline-block hb-rounded-full hb-border hb-border-[#2878FF]"
                @click="handleUploadAvatar"
              >
                更换
              </text>
            </view>
          </tm-form-item>

          <!-- 简介输入区域 -->
          <tm-form-item field="description" label="简介" :border="false" :margin="[0, 0]">
            <TmInput
              v-model="formData.description"
              :height="160"
              :font-size="28"
              :inputPadding="[16, 16]"
              placeholder="用一段话介绍你的单位，让人更了解你"
              type="textarea"
            />
          </tm-form-item>

          <!-- 身份背景择区域 -->
          <tm-form-item field="socialIdentityList" :border="false" :margin="[0, 0]">
            <template #label>
              <view class="hb-flex hb-items-center hb-justify-between hb-mb-3">
                <text class="hb-text-sm hb-text-[#333]">身份背景</text>
                <!-- 添加标签按钮 -->
                <tm-tag
                  label="+ 添加"
                  :round="6"
                  :fontSize="24"
                  :padding="[16, 12]"
                  color="#D0F7FF"
                  :font-color="'#2878FF'"
                  :follow-theme="false"
                  :margin="[0, 0]"
                  size="xs"
                  @click="handleAddTag"
                ></tm-tag>
              </view>
            </template>
            <view class="hb-flex hb-flex-wrap hb-gap-2">
              <!-- 已选标签 -->
              <view v-for="(item, index) in formData.socialIdentityList" :key="item">
                <tm-tag
                  :label="item"
                  :closable="true"
                  :round="4"
                  :fontSize="24"
                  color="#D0F7FF"
                  :font-color="'#2878FF'"
                  :follow-theme="false"
                  :margin="[0, 0]"
                  size="xs"
                  @click="handleTagClick(item, index)"
                  @close="removeTag(item)"
                ></tm-tag>
              </view>
            </view>
          </tm-form-item>
        </view>
        <BottomSubmit submitBtnLabel="保存" :submitBtnColor="'#2878FF'" :submitLoading="loading" />
      </tm-form>

      <tm-modal v-model:show="showModal" title="添加身份背景" :closeable="true">
        <view class="hb-flex hb-flex-col hb-gap-2 hb-py-3">
          <view class="hb-flex hb-items-center hb-text-sm">
            <text class="hb-text-[#333] hb-font-bold">身份背景</text>
            <text class="hb-text-red-500">*</text>
          </view>
          <tm-input v-model="tag" placeholder="请输入" :height="88" />
        </view>
        <template #button>
          <view class="hb-flex hb-justify-center hb-w-full">
            <tm-button
              :round="10"
              label="确认添加"
              :fontSize="32"
              style="width: 524rpx"
              :padding="[0, 24]"
              block
              color="#2878FF"
              @click="handleAddTagConfirm"
            ></tm-button>
          </view>
        </template>
      </tm-modal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* basicInfoEdit 编辑基础信息 */
  import { botUpdate, getByIdInfo } from '@/api/card';
  import { BotCardInfo } from '@/api/card/type';

  import { useUpload } from '@/hooks/file/useUpload';
  import { FunctionArgs } from '@vueuse/core';
  import { useUserStore } from '@/store/modules/user';
  import { debounce } from 'lodash-es';
  const userStore = useUserStore();
  const showModal = ref(false);
  const tag = ref('');

  const { chooseFile, successResult, delResultItem } = useUpload();
  let success: FunctionArgs | undefined;
  customOnload<'CardBasicInfo'>((options) => {
    success = options.success;
  });

  const handleUploadAvatar = () => {
    chooseFile({
      mediaType: 'image',
    });
  };

  const queryCardInfo = async () => {
    const res = await getByIdInfo();
    formData.name = res.name;
    formData.iconFileUrl = res.iconFileUrl;
    formData.description = res.description;
    formData.socialIdentityList = res.socialIdentityList || [];
  };
  const updIndex = ref(-1);
  const handleTagClick = (item: string, index: number) => {
    tag.value = item;
    updIndex.value = index;
    showModal.value = true;
  };

  onMounted(() => {
    queryCardInfo();
  });
  watch(
    () => successResult,
    (res) => {
      if (res.value[0]) {
        formData.iconFileUrl = res.value[0].filePath!;
        nextTick(() => {
          delResultItem(0);
        });
      }
    },
    {
      deep: true,
    },
  );

  const handleAddTag = () => {
    tag.value = '';
    updIndex.value = -1;
    showModal.value = true;
  };

  const handleAddTagConfirm = () => {
    
    if (!tag.value) {
      uni.showToast({
        title: '请输入身份背景',
        icon: 'none',
      });
      return;
    }

    if (formData.socialIdentityList.includes(tag.value)) {
      uni.showToast({
        title: '身份背景已存在',
        icon: 'none',
      });
      return;
    }

    if (updIndex.value === -1) {
      formData.socialIdentityList.push(tag.value);
    } else {
      formData.socialIdentityList[updIndex.value] = tag.value;
    }
    tag.value = '';
    updIndex.value = -1;
    showModal.value = false;
  };

  const removeTag = (item: string) => {
    formData.socialIdentityList = formData.socialIdentityList.filter((fitem) => fitem !== item);
  };

  const formData = reactive<BotCardInfo>({
    name: '',
    description: '',
    iconFileUrl: '',
    socialIdentityList: [],
  });
  const loading = ref(false);

  const handleSubmit = debounce(async (e: Tmui.tmFormSubmitResult<typeof formData>) => {
    try {
      // 表单验证
      if (!e.isPass) return;
      // 防止重复提交
      if (loading.value) return;
      loading.value = true;

      await botUpdate(formData);
      userStore.getUserInfo();
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      });
      setTimeout(() => {
        success?.();
        navigateBack();
      }, 1000);

      console.log('formData', formData);
    } catch (e) {
      console.error('表单验证失败', e);
    } finally {
      loading.value = false;
    }
  }, 200);
</script>

<style lang="scss" scoped></style>
